package com.sghd.candy.module.charge.service;

import com.sghd.candy.module.charge.manager.Charge;
import com.sghd.candy.module.charge.manager.ChargeLog;
import com.sghd.candy.module.charge.manager.ChargeLogManager;
import com.sghd.candy.module.charge.manager.ChargeManager;
import com.sghd.candy.module.player.manager.Player;
import com.sghd.candy.module.player.manager.PlayerManager;
import com.sghd.candy.module.shop.manager.ShopConfig;
import com.sghd.candy.module.shop.manager.ShopManager;
import com.sghd.candy.module.shop.service.ShopService;
import com.sghd.common.utils.model.Result;
import com.sghd.pojo.candy.charge.dto.ChargeDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author frank
 * @date 2019-02-23 16:01
 * @desc
 **/
@Service
public class ChargeService {
    @Autowired
    private ShopService shopService;
    @Autowired
    private ChargeManager chargeManager;
    @Autowired
    private ChargeLogManager chargeLogManager;
    @Autowired
    private PlayerManager playerManager;
    @Autowired
    private ShopManager shopManager;

    public Result<String> charge(ChargeDto chargeDto) {
        Player player = playerManager.load(chargeDto.getPlayerId());
        if (player == null) {
            return Result.ERROR(-2,"玩家不存在!");
        }

        ShopConfig shopConfig = shopManager.load(chargeDto.getGoodsId());
        if (shopConfig == null) {
            return Result.ERROR(-3,"商品不存在!");
        }

        Result<String> result = shopService.recharge(player, shopConfig);

        if (result.getCode() == 0) {
            ChargeLog chargeLog = chargeLogManager.getChargeLog(chargeDto.getOrderId());
            if (chargeLog == null) {
                Charge charge = chargeManager.load(chargeDto.getPlayerId());
                charge.recharge(shopConfig.getConsume());
                if (charge.getFirstChargeTime() == null) {
                    chargeLogManager.addLog(player, chargeDto.getOrderId(), shopConfig.getObtainJson(),
                            shopConfig.getConsume(), chargeDto.getIp(),true);
                    charge.setFirstChargeTime(charge.getLastChargeTime());
                } else {
                    chargeLogManager.addLog(player, chargeDto.getOrderId(), shopConfig.getObtainJson(),
                            shopConfig.getConsume(), chargeDto.getIp());
                }
                return result;
            } else {
                return Result.ERROR(-4,"订单重复!");
            }
        } else {
            return Result.ERROR(-1);
        }
    }
}
